/*
 * $Id: Desktop.java 144 2009-05-15 10:40:48Z meyer@alphatec.de $
 * 
 *
 * Copyright 2009 DeltaDesk
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package deltadesk.gui.deltagui.widget;

import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

import deltadesk.gui.deltagui.executor.ExecutorServices;
import deltadesk.gui.deltagui.graphics.Renderable;


/**
 * Desktop.
 * 
 * @author Andreas Meyer
 * @version $Revision: 144 $
 */
public class Desktop implements Renderable {

	/** The width. */
	private int width;
	
	/** The height. */
	private int height;

	/** The main composite. */
	protected Composite mainComposite;


	/**
	 * Construct the desktop.
	 * 
	 */
	public Desktop() {
		setMainComposite(new Panel());
	}

	/**
	 * @param mainComposite the mainComposite to set
	 */
	public void setMainComposite(final Composite mainComposite) {

		if(mainComposite != null) {
			this.mainComposite = mainComposite;	
		}

		if(this.mainComposite.getChildCount() > 0) {
			this.mainComposite.setFocus();
		}
		this.mainComposite.setParent(null); //TODO: not null
		this.mainComposite.setSize(width, height);
		this.mainComposite.invalidate();
	}

	/**
	 * Set the desktop size.
	 * Delegate to main control.
	 * 
	 * @param width
	 * @param height
	 */
	public void setSize(final int width, final int height) {
		this.width  = width;
		this.height = height;
		this.mainComposite.setSize(width, height);	
	}

	/**
	 * Remove all child controls from main composite and stop all threads.
	 * 
	 */
	public void shutdown() {
		
		mainComposite.removeAll();
		ExecutorServices.shutdown();
	}

	/**
	 * Render the desktop.
	 * Validate and render the mainControl.
	 * 
	 * @param g2
	 */
	public void render(final Graphics2D g2) {
		mainComposite.render(g2);
	}
	
	/**
	 * @see deltadesk.gui.deltagui.graphics.Renderable#setUnrendered()
	 */
	public void setUnrendered() {
		mainComposite.setUnrendered();
	}

	/**
	 * Post a key event.
	 * Delegate to main control.
	 * 
	 * @param ke
	 */
	public void postKeyEvent(final KeyEvent ke) {

		// Post event to parent composite of focused control
		// so that the composite is able to handle focus traversal events
		AbstractControl.focusedControl.getParent().postKeyEvent(ke);
	}

}
